package com.idopartx.phonelightning.service

import android.content.ComponentName
import android.content.Context
import android.hardware.Camera
import android.hardware.camera2.CameraManager
import android.os.Build
import android.service.notification.NotificationListenerService
import android.service.notification.StatusBarNotification
import com.idopartx.phonelightning.common.Constant
import com.idopartx.phonelightning.entity.NotifyLightningCache
import com.tencent.mmkv.MMKV

class NotificationMonitorService : NotificationListenerService() {


    // 监听器对象
    private var camera: Camera? = null
    private var isShowing: Boolean = false

    // 在收到消息时触发
    override fun onNotificationPosted(sbn: StatusBarNotification) {
        // 获取接收消息APP的包名
        val notificationPkg = sbn.packageName
        val notifyLightningCache = MMKV.defaultMMKV().decodeParcelable(
            Constant.MMKV_SAVE_NOTIFY_LIGHTNING,
            NotifyLightningCache::class.java
        ) ?: return

        if (isShowing) return

        if (notifyLightningCache.isAll != null && notifyLightningCache.isAll) {
            openStar(notifyLightningCache)
        } else {
            notifyLightningCache.selectAppList?.forEach {
                if (it == notificationPkg) {
                    openStar(notifyLightningCache)
                }
            }
        }
    }


    /**
     * 开启闪烁
     */
    private fun openStar(notifyLightningCache: NotifyLightningCache) {
        isShowing = true
        Thread {
            for (i in 0 until (notifyLightningCache.showTimes ?: 2)) {
                notifyLightningCache.lightNightList?.forEach {
                    open()
                    try {
                        Thread.sleep(it.light.toLong())
                    } catch (e: InterruptedException) {
                        e.printStackTrace()
                    }
                    close()
                    try {
                        Thread.sleep(it.night.toLong())
                    } catch (e: InterruptedException) {
                        e.printStackTrace()
                    }
                }
                if (i == ((notifyLightningCache.showTimes ?: 2) - 1)) {
                    isShowing = false
                }
            }
        }.start()
    }

    /**
     * 打开闪光灯
     *
     * @return
     */
    private fun open() {
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

                val camManager =
                    applicationContext.getSystemService(Context.CAMERA_SERVICE) as CameraManager

                val cameraId = camManager.cameraIdList[0]

                camManager.setTorchMode(cameraId, true)
            } else {
                camera = Camera.open()
                camera?.startPreview()
                val parameters = camera?.parameters
                parameters?.flashMode = Camera.Parameters.FLASH_MODE_TORCH
                camera?.parameters = parameters
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 关闭闪光灯
     *
     * @return
     */
    private fun close() {
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

                val camManager =
                    applicationContext.getSystemService(Context.CAMERA_SERVICE) as CameraManager

                val cameraId = camManager.cameraIdList[0]

                camManager.setTorchMode(cameraId, false)
            } else {
                val parameters = camera?.parameters
                parameters?.flashMode = Camera.Parameters.FLASH_MODE_OFF
                camera?.parameters = parameters
                camera?.release()
                camera = null
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 监听断开
     */
    override fun onListenerDisconnected() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            // 通知侦听器断开连接 - 请求重新绑定
            requestRebind(ComponentName(this, NotificationListenerService::class.java))
        }
    }
}